from prg.header_info import HeaderInfo
from prg.bll.config_bll import ConfigBll
from prg.common.object_message import MessageBase
import socket
import uuid


class UdpLink(MessageBase):
    def __init__(self, addr, port, aut):
        super().__init__(name="udp_" + addr.get_name())
        # config = ConfigBll.instance().get_base_config()
        self.port = port
        self.addr = addr
        self.bind_ip = ConfigBll.instance().get_ip()
        self.verification = uuid.uuid1().int
        self.aut = aut
        self.last_num = 0
        self.status = False

    def get_verification(self):
        return self.verification

    def get_port(self):
        return self.port

    def entry(self):
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_socket.bind((self.bind_ip, self.port))
            print("udp start %s" % self.addr.get_name())
            # while self.exec:
            head = HeaderInfo(client_socket=server_socket)
            if "beat" == head.get_command():
                addr_item = head.get_addr()
                print("udp beat from %s" % str(addr_item))
                head_item = head.get_head_entity(key=self.aut.aes)
                beat_num = head_item.arg.arg_dict["beat"]
                verification_code = head_item.arg.arg_dict["verification"]
                if beat_num > self.last_num and verification_code == self.addr.get_verification():
                    print("udp %s beat %s" % (self.addr.get_name(), str(beat_num)))
                    self.status = True
                    self.addr.set_status(self.status)
                    self.last_num = beat_num
                    self.addr.set_udp_addr(addr=addr_item)

